<template>
  <Modal
      :draggable="!$config.mask"
      :mask="$config.mask"
      :mask-closable="!$config.mask"
      :value="value"
      @on-ok="save"
      @on-visible-change="visibleChange"
      width="1000"
  >
    <p slot="header">
      {{ title }}<span v-if="modalData.update">{{ modalData.data.userName }}</span>
    </p>

    <Form ref="form" :model="user" :rules="rules" label-postion="top">
      <Tabs v-model="tab">
        <TabPane label="用户详情" name="a">
          <div>
            <Row :gutter="16">
              <Col span="5">
                <div :style="{backgroundImage:'url(' + profilePicture + ')',backgroundSize:'100% 100%'}"
                     class="avatar">

                </div>
              </Col>
              <Col span="19">
                <FormItem label="用户名" prop="userName">
                  <Input v-model="user.userName" :maxlength="256" placeholder=""></Input>
                </FormItem>
                <FormItem label="姓名" prop="name">
                  <Input v-model="user.name" :maxlength="64" placeholder=""></Input>
                </FormItem>
              </Col>
            </Row>
            <Row>
              <Col span="24">
                <FormItem class="h-label" label="性别" prop="genderLabel">
                  <RadioGroup v-model="user.genderLabel">
                    <Radio label="男"></Radio>&nbsp;&nbsp;&nbsp;
                    <Radio label="女"></Radio>
                  </RadioGroup>
                </FormItem>
              </Col>
            </Row>
            <Row :gutter="10">
              <Col span="12">
                <FormItem v-if="!modalData.update" label="密码" prop="password">
                  <Input ref="password" v-model="user.password" :maxlength="1024" placeholder="" type="password"></Input>
                </FormItem>
              </Col>
              <Col span="12">
                <FormItem v-if="!modalData.update" label="确认密码" prop="confirmPassword">
                  <Input v-model="user.confirmPassword" :maxlength="1024" placeholder=""
                         type="password"></Input>
                </FormItem>
              </Col>
            </Row>
            <Row :gutter="10">
              <Col span="12">
                <FormItem label="Email地址" prop="emailAddress">
                  <Input v-model="user.emailAddress" :maxlength="256" placeholder=""></Input>
                </FormItem>
              </Col>
              <Col span="12">
                <FormItem label="电话号码" prop="phoneNumber">
                  <Input v-model="user.phoneNumber" :maxlength="24" placeholder=""></Input>
                </FormItem>
              </Col>
            </Row>
            <Row>
              <Col span="24" style="margin-bottom:10px;">

                <Checkbox v-model="user.isActive">
                  激活
                </Checkbox>&nbsp;&nbsp;&nbsp;
                <Checkbox v-model="user.isLockoutEnabled">
                  启用用户锁定
                </Checkbox>

              </Col>
            </Row>
          </div>
        </TabPane>

        <TabPane :label="getRoleLabel" name="b">
          <table-select-common
              ref="tableSelect" v-model="selectedRoles" :columns="columns" :items="items"
              :total-count="totalCount" placeholder="在角色名称、角色描述中搜索" @on-change="getPage" :tag-show="false"
              display-property="roleName"
              :page-size="pageSize" :optional="optional"
              tag-color="success" :multi-select="true" :loading="$store.state.role.loading">
          </table-select-common>
        </TabPane>
        <TabPane :label="getOrganizationUnitLabel" name="c">
          <Card dis-hover>
            <tree-select-common ref="treeSelect" property="code" v-model="selectedNodes" :data="treeData"
                                :show-checkbox="true" :check-directly="true" :tag-show="false" tag-color="success"
                                :check-strictly="true"></tree-select-common>
          </Card>
        </TabPane>
      </Tabs>
    </Form>

    <div slot="footer">
      <Button icon="md-close" @click="cancel">取消</Button>
      <Button icon="md-checkmark" type="primary" @click="save">确定</Button>
    </div>
  </Modal>
</template>
<script lang="ts">
import {Component, Vue, Prop, Watch, Emit} from 'vue-property-decorator';
import AbpBase from '@/lib/abpbase';
import User from '@/store/entities/administration/user/user';
import TableSelectCommon from '@/components/select/table-select-common.vue';
import Ajax from '@/lib/ajax';
import OUTree from '@/components/organization-unit/ou-tree.vue';
import TreeSelectCommon from '@/components/select/tree-select-common.vue';

@Component({
  components: {TableSelectCommon, OUTree, TreeSelectCommon},
})
export default class UserModal extends AbpBase {
  name: string = 'UserModal';

  @Prop({type: Boolean, default: false}) value: boolean;
  @Prop({type: Object}) modalData: any;


  tab: string = 'a';
  user: User = new User();

  selectedNodes: any[] = [];
  selectedRoles: any[] = [];
  pageSize: number = 10;

  optional: any[] = [{key: 'startTime', value: '1900-01-01 00:00:00'}, {
    key: 'endTime',
    value: '2099-12-31 23:59:59'
  }, {key: 'isStatic', value: []}, {key: 'isDefault', value: []}];

  columns = [
    {
      type: 'selection',
      width: 60,
      align: 'center',
    },
    {
      title: '角色名',
      key: 'displayName',
      width: 180,
      align: 'center',
      sortable: this.$config.sorting.administration.role,
      ellipsis: true,
      tooltipTheme:'dark',
      tooltip: true,
      resizable: true,
    },
    {
      title: '系统',
      key: 'isStatic',
      width: 100,
      align: 'center',
      render: (h: any, params: any) => {
        if (params.row.isStatic) {
          return h('Icon', {
            props: {
              size: 20,
              color: this.$config.color.success,
              type: 'pandx fa fa-flag',
            },
          }, []);
        } else {
          return h('Icon', {
            props: {
              size: 20,
              color: this.$config.color.disabled,
              type: 'pandx fa fa-flag',
            },
          }, [])
        }
      },
      filters: [
        {
          label: '是',
          value: true,
        }, {
          label: '否',
          value: false,
        },
      ],
      filterRemote: (array) => {
        const index = this.optional.findIndex((item) => {
          return item.key === 'isStatic';
        });
        if (index !== -1) {
          this.optional.splice(index, 1);
        }
        this.optional.push({key: 'isStatic', value: array})
      },
      ellipsis: true,
      tooltipTheme:'dark',
      tooltip: true,
      resizable: true,
    },
    {
      title: '默认',
      key: 'isDefault',
      width: 100,
      align: 'center',
      render: (h: any, params: any) => {
        if (params.row.isDefault) {
          return h('Icon', {
            props: {
              size: 20,
              color: this.$config.color.success,
              type: 'pandx fa fa-flag',
            },
          }, []);
        } else {
          return h('Icon', {
            props: {
              size: 20,
              color: this.$config.color.disabled,
              type: 'pandx fa fa-flag',
            },
          }, [])
        }
      },
      filters: [
        {
          label: '是',
          value: true,
        }, {
          label: '否',
          value: false,
        },
      ],
      filterRemote: (array) => {
        const index = this.optional.findIndex((item) => {
          return item.key === 'isDefault';
        });
        if (index !== -1) {
          this.optional.splice(index, 1);
        }
        this.optional.push({key: 'isDefault', value: array})
      },
      ellipsis: true,
      tooltipTheme:'dark',
      tooltip: true,
      resizable: true,
    },
    {
      title: '角色描述',
      key: 'description',
      align: 'center',
      minWidth: 240,
      ellipsis: true,
      tooltipTheme:'dark',
      tooltip: true,
      resizable: true,
    },
  ];
  rules = {
    userName: [
      {
        required: true,
        message: '用户名是必须的',
        trigger: 'blur',
      },
      {
        validator: async (rule, value, callback) => {
          const response = await Ajax.post('/api/services/app/User/ValidateUserName', {
            value: value,
            id: this.modalData.update ? this.modalData.data.id : 0,
          });
          if (response.data.result.status) {
            callback();
          } else {
            callback(new Error(response.data.result.message));
          }
        },
        trigger: 'blur',
      },
    ],
    genderLabel: [
      {
        required: true,
        message: '性别是必须的',
        trigger: 'change',
      },
    ],
    password: [
      {
        required: true,
        message: '密码是必须的',
        trigger: 'blur',
      },
      {
        min: 6,
        trigger: 'blur',
        message: '密码至少要6位',
      },

    ],
    confirmPassword: [
      {
        required: true,
        message: '确认密码是必须的',
        trigger: 'blur',
      },
      {
        validator: (rule, value, callback) => {
          if (value !== (this.$refs.password as any).value) {
            callback(new Error('两次输入的密码不一致'));
          } else {
            callback();
          }
        },
        trigger: 'blur',
      },
    ],
    name: [
      {
        required: true,
        message: '姓名是必须的',
        trigger: 'blur',
      },
    ],
    emailAddress: [
      {
        required: true,
        message: 'Email地址是必须的',
        trigger: 'blur',

      },
      {
        type: 'email',
        message: 'Email地址格式不正确',
        trigger: 'blur',
      },
      {
        validator: async (rule, value, callback) => {
          const response = await Ajax.post('/api/services/app/User/ValidateEmailAddress', {
            value: value,
            id: this.modalData.update ? this.modalData.data.id : 0,
          });
          if (response.data.result.status) {
            callback();
          } else {
            callback(new Error(response.data.result.message));
          }
        },
        trigger: 'blur',
      },
    ],
    phoneNumber: [
      {
        required: true,
        message: '电话号码是必须的',
        trigger: 'blur',

      },
    ],
  };


  get profilePicture() {
    if (this.$store.state.user.profilePicture === '') {
      return './images/defaultProfilePicture.png';
    } else {
      return 'data:image/png;base64,' + this.$store.state.user.profilePicture;
    }
  }

  get title() {
    if (this.modalData.update) {
      return '编辑用户：';
    } else {
      return '新建用户';
    }
  }

  get totalCount() {
    return this.$store.state.role.pagedRoles.totalCount;
  }

  get items() {
    return this.$store.state.role.pagedRoles.items;
  }

  get treeData() {
    return this.getTreeData(null);
  }

  getRoleLabel(h) {
    return h('div', [
      h('span', '所属角色'),
      h('Badge', {
        props: {
          count: this.selectedRoles.length,
          type: 'primary',
        },
        style: {
          marginLeft: '4px',
        },
      }),
    ]);
  }

  getOrganizationUnitLabel(h) {
    return h('div', [
      h('span', '所属单位'),
      h('Badge', {
        props: {
          count: this.selectedNodes.length,
          type: 'primary',
        },
        style: {
          marginLeft: '4px',
        },
      }),
    ]);
  }


  async save() {

    (this.$refs.form as any).validate(async (valid: boolean) => {
      this.user.genderLabel === '男' ? this.user.gender = true : this.user.gender = false;
      if (valid) {
        await this.$store.dispatch({
          type: 'user/createOrUpdateUser',
          data: {
            user: this.user,
            assignedRoleNames: this.selectedRoles.map((item) => {
              return item.displayName;
            }),
            organizationUnits: this.selectedNodes.map((item) => {
              return item.extra.id;
            }),
          },
        });
        if (this.modalData.update) {
          this.$Message.success({
            background: true,
            content: '用户 ' + this.user.userName + ' 已更新成功',
            duration: this.$config.duration,
          });
        } else {
          this.$Message.success({
            background: true,
            content: '用户 ' + this.user.userName + ' 已新建成功',
            duration: this.$config.duration,
          });
        }
        this.$emit('save-success');
        this.$emit('input', false);
      }
    });
  }

  cancel() {
    this.$emit('input', false);
  }

  async visibleChange(value: boolean) {
    if (!value) {
      this.reset();
      this.$emit('input', value);
    } else {
      await this.getPage({
        sorting: '',
        filter: '',
        maxResultCount: this.pageSize,
        skipCount: 0,
        connectId: 0,
        startTime: '1900-01-01 00:00:00',
        endTime: '2099-12-31 23:59:59',
        isStatic: [],
        isDefault: [],
      });
      if (this.modalData.update) {

        this.user = this.$store.state.user.userForEdit.user;
        this.user.gender ? this.user.genderLabel = '男' : this.user.genderLabel = '女';

        this.selectedRoles = this.$store.state.user.userForEdit.roles.filter((item) => {
          return item.isAssigned;
        });
        this.selectedRoles.forEach((item) => {
          this.$set(item, 'id', item.roleId);
          this.$set(item, 'name', item.roleName);
          this.$set(item, 'displayName', item.roleName);
        });

        (this.$refs.treeSelect as any).setSelectedNode(this.treeData, this.$store.state.user.userForEdit.memberedOrganizationUnits);
      } else {
        (this.$refs.treeSelect as any).setSelectedNode(this.treeData, [])
      }
    }
  }

  async getPage(args) {
    await this.$store.dispatch({
      type: 'role/obtainPagedRoles',
      data: args,
    });
  }


  reset() {
    (this.$refs.form as any).resetFields();

    this.selectedRoles = [];
    (this.$refs.tableSelect as any).filter = '';
    (this.$refs.tableSelect as any).sorting = '';
    (this.$refs.tableSelect as any).currentPage = 1;

    this.selectedNodes = [];

    this.tab = 'a';
    this.user = new User();

  }

  getTreeData(parentId: number) {
    let data: any[] = [];
    const o = this.$store.state.ou.list;
    o.forEach((item) => {
      if (item.parentId === parentId) {
        let node: any = {};
        node.title = item.displayName;
        node.expand = true;
        node.code = item.code;
        node.extra = item;
        node.children = this.getTreeData(item.id);
        data.push(node);
      }
    });
    return data;
  }




  async created() {
    await this.$store.dispatch({
      type: 'ou/getOrganizationUnits',
    });
  }
}
</script>

<style lang="less" scoped>
.avatar {
  margin-top: 0;
  width: 160px;
  height: 160px;
  border: 1px solid #ccc;
  border-radius: 5px;
}

.ivu-tabs-tabpane::v-deep {
  .ivu-card-body {
    height: 464px;
    overflow-y: auto;
  }

  .ivu-card-body::-webkit-scrollbar {
    width: 4px;
    background-color: #fff;
  }

  .ivu-card-body::-webkit-scrollbar-thumb {
    border-radius: 2px;
    -webkit-box-shadow: inset 0 0 1px rgba(0, 0, 0, .3);
    background-color: #e8eaec;
  }

  .ivu-card-body::-webkit-scrollbar-track {
    -webkit-box-shadow: inset 0 0 1px rgba(0, 0, 0, .3);
    border-radius: 2px;
    background-color: #fff;
  }
}


</style>
